﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RoboSensors.Tools
{
    public class TextLog : ILogWriter
    {
        string m_FileNmae;
        private static readonly Queue<MsgInfo> m_LogStringQueue = new Queue<MsgInfo>();
        FileStream fs;
        StreamWriter sw;
        Thread thread;
        bool isStart = true;
        public TextLog(string FileName)
        {
            m_FileNmae = FileName;
            fs = new FileStream(FileName, FileMode.Create);
            sw = new StreamWriter(fs);
            WriteLogInfo(new MsgInfo("TextLog Init......\n",ErrLevel.Log));
            thread = new Thread(new ThreadStart(WriteThread));
            thread.Start();
        }

        public void WriteLogInfo(MsgInfo msg)
        {
            //lock(m_LogStringQueue)
            //{
                m_LogStringQueue.Enqueue(msg);
            //}
        }

        private void WriteLog(MsgInfo msg)
        {
            try
            {
                sw.WriteLine(string.Format("[{0}] {1}：{2}", msg.ErrLevel.ToString(), DateTime.Now.ToString("hh:mm:ss:fff"), msg.Content));
               // sw.Write(msg.ErrLevel.ToString()+" "+ DateTime.Now.ToString("hh:mm:ss:fff")+": " +msg.Content+"\n");
            }
            catch (Exception)
            {

                throw;
            }
        }

        public void Close()
        {
            isStart = false;
            thread.Abort();
            sw.Close();
            fs.Close();
        }

        public void WriteThread()
        {
            while(isStart)
            {
                //lock (m_LogStringQueue)
                //{
                    if (m_LogStringQueue.Count > 0)
                    {
                        WriteLog(m_LogStringQueue.Dequeue());
                        sw.Flush();
                    }
                    else
                    {
                       // m_LogStringQueue.Enqueue(new MsgInfo("12345"));
                        Thread.Sleep(10);
                    }    
                //}
            }
        }
    }
}
